package com.cn.shuangzi.loginplugin.activity;

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.cn.shuangzi.R;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.activity.SZInterfaceActivity;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.loginplugin.bean.SZUserInfo;
import com.cn.shuangzi.loginplugin.common.socialized.ThirdLogin;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.view.pop.BottomCtrlPop;
import com.cn.shuangzi.view.pop.FilterPop;
import com.cn.shuangzi.view.pop.common.CtrlItem;
import com.cn.shuangzi.view.shape_imgview.CustomShapeImageView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

/**
 * Created by CN on 2018-1-8.
 */

public abstract class SZLoginActivity extends SZBaseActivity implements ThirdLogin
        .OnThirdLoginResponseListener, SZInterfaceActivity, View.OnClickListener {
    public static ThirdLogin thirdLogin;
    private TextView txtAppName;
    private BottomCtrlPop filterPop;
    private CustomShapeImageView imageViewLogo;
    public CheckBox chkBoxAgree;
    public Button imgLogin;
    public Button btnLoginTypeMore;
    private boolean isRequestingUserInfo;
    private String loginType;
    @Override
    protected int onGetChildView() {
        return R.layout.activity_login;
    }

    @Override
    protected void onBindChildViews() {
        imageViewLogo = findViewById(R.id.imgLogoText);
        txtAppName = findViewById(R.id.txtAppName);
        chkBoxAgree = findViewById(R.id.chkBoxAgree);
        btnLoginTypeMore = findViewById(R.id.btnLoginTypeMore);
        imgLogin = findViewById(R.id.imgLogin);
    }

    @Override
    protected void onBindChildListeners() {
        btnLoginTypeMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOtherLogin();
            }
        });
    }

    @Override
    protected void onChildViewCreated() {
        loginType = getStringExtra();
        onChildViewCreatedPre();
        initLoginType();
        setTitleTxt(R.string.txt_login);
        showBackImgLeft(getBackImgLeft());
        txtAppName.setText(getAppName());
        try {
            imageViewLogo.setImageResource(getLogoRes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        btnLoginTypeMore.setVisibility(isShowMoreLoginType()?View.VISIBLE:View.GONE);
    }
    @Override
    protected void onReloadData(boolean isRefresh) {
    }
    private void initLoginType(){
        if(loginType!=null){
            switch (loginType){
                case ThirdLogin.WE_CHAT_PLATFORM:
                    imgLogin.setText("微信登录");
                    imgLogin.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(chkBoxAgree.isChecked()) {
                                loginWeChat();
                            }else{
                                SZUtil.showAgreeTwoProtocolAlert(getActivity(), "同意并登录", getString(R.string.privacy_policy_symbol),
                                        getPrivacyUrl(), getString(R.string.service_agreement_symbol), getProtocolUrl(), getWebViewActivity(), new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                chkBoxAgree.setChecked(true);
                                                loginWeChat();
                                            }
                                        });
                            }
                        }
                    });
                    break;
                case ThirdLogin.ALIPAY_PLATFORM:
                    imgLogin.setText("支付宝登录");
                    imgLogin.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(chkBoxAgree.isChecked()) {
                                getAlipayAuthInfo();
                            }else{
                                SZUtil.showAgreeTwoProtocolAlert(getActivity(), "同意并登录", getString(R.string.privacy_policy_symbol),
                                        getPrivacyUrl(), getString(R.string.service_agreement_symbol), getProtocolUrl(), getWebViewActivity(), new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                chkBoxAgree.setChecked(true);
                                                getAlipayAuthInfo();
                                            }
                                        });
                            }
                        }
                    });
                    break;
            }
        }else{
            imgLogin.setText("微信登录");
            imgLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(chkBoxAgree.isChecked()) {
                        loginWeChat();
                    }else{
                        SZUtil.showAgreeTwoProtocolAlert(getActivity(), "同意并登录", getString(R.string.privacy_policy_symbol),
                                getPrivacyUrl(), getString(R.string.service_agreement_symbol), getProtocolUrl(), getWebViewActivity(), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        chkBoxAgree.setChecked(true);
                                        loginWeChat();
                                    }
                                });
                    }
                }
            });
        }
    }
    private void showOtherLogin() {
        List<CtrlItem> ctrlItemList = new ArrayList<>();
        ctrlItemList.add(new CtrlItem("手机号码登录", "手机号码登录", false));
        filterPop = new BottomCtrlPop(this, ctrlItemList, new FilterPop.OnItemClickListener() {
            @Override
            public void onItemChecked(int position, CtrlItem ctrlItem) {
                filterPop.dismiss();
                startActivity(getPhoneLoginActivity(), true);
            }
        }, false);
        filterPop.showOnAnchorFromBottom(getBaseView());
    }
    private void loginAlipay(String authInfo){
        if (SZUtil.isAppInstalled("com.eg.android.AlipayGphone")) {
            thirdLogin = new ThirdLogin(this, ThirdLogin.ALIPAY_PLATFORM,authInfo, this);
            thirdLogin.login();
        } else {
            SZToast.warning("您还没有安装支付宝！");
        }
    }
    private void getAlipayAuthInfo(){
        if (!SZUtil.isAppInstalled("com.eg.android.AlipayGphone")) {
            SZToast.warning("您还没有安装支付宝！");
            return;
        }
        showBar();
        request(SZRetrofitManager.getInstance().getSZRequest().getAlipayAuthInfo(SZConst.ALIPAY), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                closeBar();
                loginAlipay(data);
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                closeBar();
            }
        });
    }
    private void loginQQ() {
        thirdLogin = new ThirdLogin(this, ThirdLogin.QQ_PLATFORM, this);
        thirdLogin.login();
    }

    private void loginWeChat() {
        if (SZUtil.isAppInstalled("com.tencent.mm")) {
            thirdLogin = new ThirdLogin(this, ThirdLogin.WE_CHAT_PLATFORM, this);
            thirdLogin.login();
        } else {
            SZToast.warning("您还没有安装微信!");
        }
    }

    @Override
    public void onSuccess(String thirdId) {
        if(!isRequestingUserInfo) {
            isRequestingUserInfo = true;
            showBar();
            if(ThirdLogin.ALIPAY_PLATFORM.equals(loginType)){
                request(SZRetrofitManager.getInstance().getSZRequest().loginThirdV2("ALIPAY",thirdId), new SZCommonResponseListener() {
                    @Override
                    public void onResponseSuccess(String data) {
                        dealToken(SZRetrofitManager.getInstance().getSZRequest().getTokenByCode(data));
                    }
                    @Override
                    public void onResponseError(int errorCode, String errorMsg) {
                        closeBar();
                        isRequestingUserInfo = false;
                    }
                });
            }else {
                request(SZRetrofitManager.getInstance().getSZRequest().loginThirdV2(getThirdPlatform() == null ? "WECHAT" : getThirdPlatform(), thirdId), new SZCommonResponseListener() {
                    @Override
                    public void onResponseSuccess(String data) {
                        Observable observable = getDealTokenObservable(data);
                        if (observable == null) {
                            onGetTokenSuccess(data);
                        } else {
                            dealToken(observable);
                        }
                    }

                    @Override
                    public void onResponseError(int errorCode, String errorMsg) {
                        closeBar();
                        isRequestingUserInfo = false;
                    }
                });
            }
        }
    }
    public void dealToken(Observable observable){
        request(observable, new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                closeBar();
                SZUserInfo userInfo = null;
                try {
                    userInfo = new Gson().fromJson(data, SZUserInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                onDealTokenSuccess(userInfo,data);
            }
            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                closeBar();
                isRequestingUserInfo = false;
            }
        });
    }
    @Override
    public void onFailed() {
        closeBar();
        SZToast.warning(getString(R.string.txt_login_failed));
    }

    @Override
    public void onCancel() {
        closeBar();
        SZToast.warning(getString(R.string.txt_login_cancelled));
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (thirdLogin != null && thirdLogin.getLoginType() != null) {
//            switch (thirdLogin.getLoginType()) {
//                case ThirdLogin.QQ_PLATFORM:
//                    if (thirdLogin.getQQIUiListener() != null)
//                        Tencent.onActivityResultData(requestCode, resultCode, data, thirdLogin.getQQIUiListener());
//                    break;
//            }
//        }
//    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.txtProtocol) {
            startActivity(getProtocolUrl(), getWebViewActivity());
        } else if (i == R.id.txtPrivacy) {
            startActivity(getPrivacyUrl(), getWebViewActivity());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        thirdLogin = null;
    }

    public String getThirdPlatform() {
        return null;
    }

    public boolean isRequestingUserInfo() {
        return isRequestingUserInfo;
    }

    public void setRequestingUserInfo(boolean requestingUserInfo) {
        isRequestingUserInfo = requestingUserInfo;
    }
    public boolean isShowMoreLoginType(){
        return true;
    }
    public abstract Class getWebViewActivity();

    public abstract String getPrivacyUrl();

    public abstract String getProtocolUrl();

    public abstract Class<?> getPhoneLoginActivity();

    public abstract int getLogoRes();

    public abstract int getAppName();

    public abstract void onGetTokenSuccess(String token);

    public abstract Observable getDealTokenObservable(String token);

    public abstract void onDealTokenSuccess(SZUserInfo userInfo,String data);
}
